package cn.jhc.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.List;
import java.util.concurrent.CountDownLatch;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.ws.Response;

import org.apache.commons.dbutils.QueryRunner;

import com.oracle.webservices.internal.api.databinding.Databinding.Builder;
import com.sun.xml.internal.ws.api.model.wsdl.editable.EditableWSDLService;

import cn.jhc.Global;
import cn.jhc.bean.Article;
import cn.jhc.db.ArticleDao;
import jdk.nashorn.internal.runtime.JSONFunctions;

/**
 * Servlet implementation class ListArticlesServlet
 */
@WebServlet("/list.do")
public class ListArticlesServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String type = request.getParameter("type");
		if(type ==null) {
			type = "html";
		}
		String pageNum = request.getParameter("page");
	    int currentrage= 0;
	    
		try {
		int currentPage = Integer.valueOf(pageNum).intValue();
		}catch (NumberFormatException e1) {
			e1.printStackTrace();
		int currentPage = 0;
			
		}
		
		QueryRunner runner = (QueryRunner) request.getServletContext().getAttribute(Global.KEY_QUERY_RUNNER);
		List<Article> articles = null;
		long count = 0;
		try {
			articles = ArticleDao.find(runner, 0);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		long total = count % Global.PAGE_SIZE == 0 ? count / Global.PAGE_SIZE :
			count / Global.PAGE_SIZE +1;
		if(type.equals("html")) {
		//两种解决方案：一是session + redirect，二是request + forward。
		//方案一
//		request.getSession().setAttribute("articles", articles);
//		response.sendRedirect("./list.jsp");
		
		//方案二
		request.setAttribute("articles", articles);
		request.getRequestDispatcher("./list.jsp").forward(request, response);
		request.setAttribute("total", total);
		request.getRequestDispatcher("./list.jsp").forward(request, response);
	
	} else if(type.equals("json")) {
		Response.setContentType("application/json;charset=utf8");
	
		JsonArrayBuilder builder = Json.createArrayBuilser();
		
		for(Article article : articles) {
			builder.add(article.toJson());
		}
		PrintWriter writer =response.getWriter();
		writer.print(builder.build().toString());
	}
	}
}
